﻿using AvoidForgettingApi.Common;
using AvoidForgettingApi.Entities.Dtos;
using AvoidForgettingApi.Entities.Models;
using AvoidForgettingApi.Entities.Models.User;
using AvoidForgettingApi.JWT;
using FreeSql;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AvoidForgettingApi.Controllers
{
    /// <summary>
    /// User Api
    /// </summary>

    public class UserController : CommonBaseController
    {
        IConfiguration Configuration;
        BaseRepository<Bank_User> resUser;
        private readonly ITokenHelper tokenHelper = null;
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="_tokenHelper"></param>
        /// <param name="_userDto"></param>
        /// <param name="configuration"></param>
        public UserController(ITokenHelper _tokenHelper, BaseRepository<Bank_User> _userDto, IConfiguration configuration)
        {
            tokenHelper = _tokenHelper;
            resUser = _userDto;
            Configuration = configuration;
            
        }

        /// <summary>
        /// 登录
        /// code + 用户凭证
        /// </summary>
        /// <remarks>
        /// 请求示例:
        /// 
        ///     {
        ///        "code": "admin",
        ///        "password": "xxxxxxxxxxxxx"
        ///     }
        ///
        /// </remarks>
        /// <param name="user">工号+密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<CommonResponse>> Login(LoginRequest user)
        {
            var response = new CommonResponse();

            if (string.IsNullOrEmpty(user.Code) || string.IsNullOrEmpty(user.Credential))
            {
                response.Code = -1;
                response.Message = "用户名密码不能为空";
                return response;
            }
            string salt = Configuration.GetSection("BaseInfo").GetSection("Salt").Value;
            string credential = CommonHelper.Md5String(user.Credential + salt);
            if (await resUser.Select.AnyAsync(u => u.Code == user.Code && u.Credential == credential))
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>
                    {
                        { "usercode", user.Code },
                        { "role","admin" },
                        { "createTime", DateTime.Now}
                    };
                response.Code = 0;
                response.Message = "登录成功";
                response.TokenInfo = tokenHelper.CreateToken(keyValuePairs);
            }
            else
            {
                response.Code = -1;
                response.Message = "用户名或者密码不正确";
            }

            return response;
        }


        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddInfo(AddUserRequest info)
        {
            string Message;
            try
            {

                var isExist = await resUser.Select.AnyAsync(u => u.Code == info.Code);
                if (isExist)
                {
                    Message = "登录名重复!";
                }
                else
                {
                    string salt = Configuration.GetSection("BaseInfo").GetSection("Salt").Value;
                    var insertResult = await resUser.InsertAsync(new Bank_User
                    {
                        Code = info.Code,
                        Credential = CommonHelper.Md5String(info.Credential + salt),
                        Disable = false,
                        IsAdmin = info.IsAdmin,
                        Name = info.Name,
                        OrgCode = info.OrgCode,
                        Phone = info.Phone
                    });
                    Message = insertResult == null ? "添加失败" : "添加成功";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }

            return Ok(Message);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>  
        [HttpGet]
        public async Task<IActionResult> Info(string usercode)
        {
            try
            {
                //int a = 0;
                //Console.WriteLine((10 / a).ToString());
            }
            catch (Exception ex)
            {
               return Ok(ex);
            }
            return Ok(await resUser.Select.Where(u => u.Code == usercode).FirstAsync());
        }
    }
}


